package com.magicborrow.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.activity.PushStuffActivity;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ghost on 16/3/28.
 */
public class DraftRentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private static final int TYPE_FOOT = 0;
    private static final int TYPE_NORMAL = 1;
    private ArrayList<StuffBean> mData;
    private Context mContext;
    private LayoutInflater mLayoutInflater;

    public DraftRentAdapter(Context pContext){
        this.mContext = pContext;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    public void setData(ArrayList<StuffBean> pData){
        this.mData = pData;
    }

    public ArrayList<StuffBean> getData(){
        return this.mData;
    }

    @Override
    public int getItemViewType(int position) {
        if(position+1 == getItemCount()){
            return TYPE_FOOT;
        }else{
            return TYPE_NORMAL;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == TYPE_FOOT){
            View view = mLayoutInflater.inflate(R.layout.load_more_footer,null);
            view.setTag("foot");
            return new FootViewHolder(view);
        }else if(viewType == TYPE_NORMAL){
            View view = mLayoutInflater.inflate(R.layout.draft_rent_item,null);
            return new AlreadyPublishedRentViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if(holder instanceof AlreadyPublishedRentViewHolder){
            AlreadyPublishedRentViewHolder hold = (AlreadyPublishedRentViewHolder)holder;
            final StuffBean bean = mData.get(position);
            hold.tvName.setText(bean.getName());
            hold.saveTime.setText("保存时间: "+bean.getCreated());
            hold.describle.setText(bean.getDescription());
            hold.wantborrowday.setText(bean.getLendMode()+"");
            hold.location.setText(bean.getAddress());
            hold.ll_img.removeAllViews();
            for (StuffBean.ImagesEntity img : bean.getImages()) {
                ImageView imv = createImageView(img.getOrigin());
                hold.ll_img.addView(imv);
            }
            hold.edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("data",bean);
                    intent.setClass(mContext, PushStuffActivity.class);
                    mContext.startActivity(intent);
                }
            });
            hold.onekeypublish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String,String> params = new HashMap<>();
                   // params.put("id",bean.getId()+"");
                    params.put("acc_token", UserTools.getUser(mContext).getAcc_token());
                    VolleyTool.post(Constants.ONE_KEY_PUBLISHE+"/"+bean.getId(), params, new VolleyTool.HTTPListener() {
                        @Override
                        public <T> void onResponse(T t, int requestCode) {
                            try {
                                JSONObject json = new JSONObject(t.toString());
                                int code = json.getInt("code");
                                String message = json.getString("message");
                                if(code == 0){
                                    Toast.makeText(mContext,"发布成功",Toast.LENGTH_SHORT).show();
                                    DraftRentAdapter.this.getData().remove(bean);
                                    DraftRentAdapter.this.notifyItemRemoved(position);
                                }else{
                                    Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                            }
                        }
                        @Override
                        public void onErrorResponse(VolleyError error, int requestCode) {
                            Toast.makeText(mContext,"服务器暂时无法连接",Toast.LENGTH_SHORT).show();
                        }
                    },0,null);
                }
            });
        }
    }

    @NonNull
    private ImageView createImageView(String s) {
        final ImageView imv = new ImageView(mContext);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.setMargins(mContext.getResources().getDimensionPixelOffset(R.dimen.layout_padding_nor), 0, 0, 0);
        imv.setScaleType(ImageView.ScaleType.FIT_XY);
        imv.setLayoutParams(params);
        // imv.setImageDrawable(context.getResources().getDrawable(R.mipmap.img_default));
        ImageLoader.getInstance().loadImage(Constants.ADDRESS + s, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                // super.onLoadingComplete(imageUri, view, loadedImage);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imv.getLayoutParams();
                //  layoutParams.width = loadedImage.getWidth() * layoutParams.height / loadedImage.getHeight();
                layoutParams.width = loadedImage.getWidth() * mContext.getResources().getDimensionPixelOffset(R.dimen._150dp) / loadedImage.getHeight();
                Log.i("======", layoutParams.width + "===" + layoutParams.height);
                imv.setLayoutParams(layoutParams);
                imv.setImageBitmap(loadedImage);
            }
        });
        //  ImageLoader.getInstance().displayImage(Constants.ADDRESS + s, imv);
        return imv;
    }

    @Override
    public int getItemCount() {
        return mData.size()+1;
    }



    public class AlreadyPublishedRentViewHolder extends RecyclerView.ViewHolder {
        private LinearLayout ll_img;
        private TextView tvName;
        private TextView saveTime;
        private TextView describle;
        private TextView wantborrowday;
        private TextView location;
        private TextView edit;
        private TextView onekeypublish;

        public AlreadyPublishedRentViewHolder(View view) {
            super(view);
            ll_img = (LinearLayout)view.findViewById(R.id.ll_img);
            tvName = (TextView) view.findViewById(R.id.tv_name);
            saveTime = (TextView)view.findViewById(R.id.time);
            describle = (TextView)view.findViewById(R.id.describle);
            wantborrowday = (TextView)view.findViewById(R.id.wantborrowday);
            location = (TextView)view.findViewById(R.id.location);
            edit = (TextView)view.findViewById(R.id.edit);
            onekeypublish = (TextView)view.findViewById(R.id.onekeypublish);
        }
    }

    public class FootViewHolder extends RecyclerView.ViewHolder{

        public FootViewHolder(View itemView) {
            super(itemView);
        }

    }

}
